<?php
	defined('_JEXEC') or die('Restricted access');
    //  System Definition
   	define( SOURCE_FOLDER, 'ce' );
    define( CE_VERSION, '0.9.0.3' );
    //  User Definition
    require('default_site.php');
    //echo DB_VERSION;
	// DB Version
    if (! defined(DB_VERSION))
    {
        if ((SITE_VERSION == '0.9.0.0' ) || (SITE_VERSION == '0.9.0.1' ))
            define( DB_VERSION, '0.9.0.0' );
		else if (SITE_VERSION == '0.9.0.2' )
            define( DB_VERSION, '0.9.0.1' );
		else if (SITE_VERSION == '0.9.0.3' )
            define( DB_VERSION, '0.9.0.2' );			
        else
            define( DB_VERSION, '0.0.0.0' );	
    }        
	//echo DB_VERSION;	

    // Check source version
    if (CE_VERSION != SITE_VERSION)
        die('Mismatched CuteEngine Version ');
    ob_start();
    require_once(SOURCE_FOLDER.DIRECTORY_SEPARATOR."namespaces".DIRECTORY_SEPARATOR."url_parameters_namespace.php");
    //
    global $g_url_parameters_namespace;
    //if ($g_url_parameters_namespace->current_site == 'offline')
    //{
        echo "inizio rederizzazione ore " . date( "d/m/Y H.i.s ", time() ) ."<br>";
    //} 
    //
    if (SITE_FOLDER != '')
        define(CUTEENGINE_PATH,SITE_ROOT.DIRECTORY_SEPARATOR.SITE_FOLDER.DIRECTORY_SEPARATOR);
    else
        define(CUTEENGINE_PATH,SITE_ROOT.DIRECTORY_SEPARATOR);            
    //
    define(CUTEENGINE_COMPONENTS_PATH,CUTEENGINE_PATH.SOURCE_FOLDER.DIRECTORY_SEPARATOR."php_components".DIRECTORY_SEPARATOR);    
    define(CUTEENGINE_NAMESPACES_PATH,CUTEENGINE_PATH.SOURCE_FOLDER.DIRECTORY_SEPARATOR."namespaces".DIRECTORY_SEPARATOR);    
    define(CUTEENGINE_BASE_COMPONENTS_PATH,CUTEENGINE_COMPONENTS_PATH."base_components".DIRECTORY_SEPARATOR);
    define(CUTEENGINE_UTILS_COMPONENTS_PATH,CUTEENGINE_COMPONENTS_PATH."utils_component".DIRECTORY_SEPARATOR);
    define(CUTEENGINE_PATH_SITES,CUTEENGINE_PATH.SOURCE_FOLDER.DIRECTORY_SEPARATOR."sites".DIRECTORY_SEPARATOR);
    define(CUTEENGINE_PATH_CUSTOM_FILES,CUTEENGINE_PATH_SITES."custom_files".DIRECTORY_SEPARATOR);
    define(CUTEENGINE_LANGUAGES_COMPONENTS_PATH,CUTEENGINE_COMPONENTS_PATH."languages".DIRECTORY_SEPARATOR);    
    define(CUTEENGINE_CUSTOM_LANGUAGES_PATH,CUTEENGINE_PATH_CUSTOM_FILES."languages".DIRECTORY_SEPARATOR);    
    define(CUTEENGINE_PARTS_PATH,CUTEENGINE_BASE_COMPONENTS_PATH."parts".DIRECTORY_SEPARATOR);
    define(CUTEENGINE_BASE_PART_PATH,CUTEENGINE_PARTS_PATH."base_part".DIRECTORY_SEPARATOR);
    define(CUTEENGINE_FIELDS_PATH,CUTEENGINE_BASE_COMPONENTS_PATH."fields".DIRECTORY_SEPARATOR);
    define(CUTEENGINE_BASE_FIELD_PATH,CUTEENGINE_FIELDS_PATH."base_field".DIRECTORY_SEPARATOR);
    define(CUTEENGINE_ACTIONS_PATH,CUTEENGINE_BASE_COMPONENTS_PATH."actions".DIRECTORY_SEPARATOR);
    define(CUTEENGINE_BASE_ACTION_PATH,CUTEENGINE_ACTIONS_PATH."base_action".DIRECTORY_SEPARATOR);
    define(CUTEENGINE_STEPS_PATH,CUTEENGINE_BASE_COMPONENTS_PATH."steps".DIRECTORY_SEPARATOR);
    define(CUTEENGINE_BASE_STEP_PATH,CUTEENGINE_STEPS_PATH."base_step".DIRECTORY_SEPARATOR);
	
    //
    require_once(CUTEENGINE_BASE_COMPONENTS_PATH."user_agent_class.php");
    require_once(CUTEENGINE_BASE_COMPONENTS_PATH."query_parameters_class.php");
    require_once(CUTEENGINE_BASE_COMPONENTS_PATH."log_class.php");
	//require_once(CUTEENGINE_BASE_ACTION_PATH."base_action_class.php");
	//require_once(CUTEENGINE_ACTIONS_PATH."action_list_from_db".DIRECTORY_SEPARATOR."action_list_from_db.php");

    
    //
    // __autoload
    //
    if (! function_exists(__autoload))
    {
        function __autoload($class_name) 
        {
            
			//echo "ambient_namespace __autoload($class_name) <br>";
            //echo "ambient_namespace __autoload($class_name) <br>";
            ob_start() ;
			global $g_ambient_namespace;
            $g_ambient_namespace->log->add_a_report_log("ambient_namespace __autoload($class_name)");
			//
            $local_class_name = substr($class_name,2);  // exclude "t_" prefix
            //echo "ambient_namespace __autoload($class_name) <br>";
            //$g_ambient_namespace->log->add_log_on_page("ambient_namespace __autoload($class_name)");
            $local_component_file = CUTEENGINE_COMPONENTS_PATH."$local_class_name/$local_class_name.php";
			$local_field_file = CUTEENGINE_FIELDS_PATH."$local_class_name/$local_class_name.php";
            $local_action_file = CUTEENGINE_ACTIONS_PATH."$local_class_name/$local_class_name.php";
            $local_step_file = CUTEENGINE_STEPS_PATH."$local_class_name/$local_class_name.php"; 
			$local_part_file = CUTEENGINE_PARTS_PATH."$local_class_name/$local_class_name.php"; 
            //echo $local_step_file;
            if (($g_ambient_namespace->autoload_content === 'components_content') || (file_exists($local_component_file)))
            {
                //echo "local_component_file: $local_component_file <br>";
                require_once $local_component_file;
            }
            else if (($g_ambient_namespace->autoload_content === 'fields_content') || (file_exists($local_field_file)))
            {
                require_once $local_field_file;
            }            
            else if (($g_ambient_namespace->autoload_content === 'actions_content') || (file_exists($local_action_file)))
            {
                require_once $local_action_file;
            }
            else if (($g_ambient_namespace->autoload_content === 'steps_content') || (file_exists($local_step_file)))
            {
                
                require_once $local_step_file;
            }           
            else if (($g_ambient_namespace->autoload_content === 'parts_content') || (file_exists($local_part_file)))
            {
                
                require_once $local_part_file;
            } 			
            else    
            {   
                if ($class_name == 't_editing_tags')
                {
                    require_once (CUTEENGINE_BASE_COMPONENTS_PATH."editing_tags_class.php");
                }
				if ($class_name == 't_html_timer')
                {
                    require_once (CUTEENGINE_COMPONENTS_PATH."html_page/html_page.php");
                }
                else
                {
                    //echo $class_name;
                    $g_ambient_namespace->log->add_log_on_page("Unable to load class '$class_name'");
                    $g_ambient_namespace->log->add_log_error("Unable to load class '$class_name'");
                }
            }    
            ob_end_clean();
        }	
    }
	
	class t_user
	{
		public $email = '';
		// G
		public $groups = array();
		public $name = '';
		// I
		public $id = 0;
		
		// methods
		// S
		public function set_info($a_email,$a_groups,$a_name,$a_id)
        {
			//echo "a_email: $a_email - a_groups: $a_groups - a_name: $a_name<br>";
			$this->email = $a_email;
			$this->groups = explode(',',$a_groups);
			$this->name = $a_name;
			if ((!isset($a_id)) || ($a_id == ''))
				$this->id = 0;
			else
				$this->id = $a_id;
		}
		public function check_user_groups($a_groups)
        {
			
			//echo "a_groups: $a_groups<br>";
			$local_groups = explode(',',$a_groups);
			if (in_array(0, $local_groups))
				return true;
			//print_r($this->groups);
			//print_r($local_groups);

			foreach ($this->groups As $local_index => $local_group)
            {
				if (in_array($local_group, $local_groups))
					return true;
			}
			return false;
		}
		
	}
	
    class t_ambient_namespace
    {
        // method declaration
        // public
        // A
        public $autoload_content = '';
        // C
        public $cookie_request = null;
        public $connection = null; //t_connection
        public $current_domian = false;
        public $current_port = false;
        public $current_site = null;
		// D
		public $date_separator = '';
		public $date_validation_strings = '';
        
        // E
        public $edit_mode = false;

        // F
        public $fast_parameter = '';
		// M 
		public $mysql_character_set = 'utf8';
		public $mysql_time_zone = '';
		public $money_local = '';
        //L
        public $language = '';
        public $log = false; //t_log
		
        // O
        public $before_start_session = null;
		// P
		public $parent_page = '';
		public $php_day_format = '';
		public $php_date_format = '';
		public $php_date_format_label = '';
		public $php_money_format_label = '';
		public $php_hour_format = '';
		public $php_minute_format = '';
		public $php_month_format = '';	
		public $php_second_format = '';		
		public $php_time_format = '';
		public $php_time_format_label = '';
		public $php_year_format = '';
        // S
        public $script_name = false;
		// T
		public $time_separator = '';
        public $time_validation_strings = '';
        // U
        public $user_agent = false; // t_user_agent_component;
		
        //
        // method declaration
        // public
        public function __construct() 
        {
            $this->connection = new t_connection;
            //echo "ciao";
            global $g_url_parameters_namespace;

            // Ambient initialization 
            $this->current_domian = $_SERVER['SERVER_NAME'];
            //echo "this->current_domian:$this->current_domian";
            $this->current_port = $_SERVER['SERVER_PORT']; 
            if ($this->current_port == '80')
                $this->current_port =  '';
            //
            $this->current_site = $g_url_parameters_namespace->current_site;
            $this->fast_parameter = $g_url_parameters_namespace->fast_parameter;
            $this->script_name = $_SERVER['SCRIPT_NAME'];
            //echo "this->script_name: $this->script_name";
            $this->user_agent = new t_user_agent_component;
            //  LOG
            $this->log = new t_log;
            $this->log->save_error_to_db = false;
            if ($g_url_parameters_namespace->current_site == 'offline')
            {
                $this->log->show_on_page = true;
            }  
            //

            
        }
        // C
        public function close_db_connection()
        {
            $this->connection->close_connection();
            $this->log->add_log_on_page("CONNESISONE A DB CHIUSA");
        }
		public function check_user_permission($a_comp_permission)
        {
			global $g_cuteengine;
			$local_return = (($this->is_there_a_logged_user()) && ($g_cuteengine->user->check_user_groups($a_comp_permission)));
			//echo "check_user_permission(a_comp_permission:$a_comp_permission == g_cuteengine->user->groups: ".$g_cuteengine->user->groups.") result: $local_return<br>";
			return $local_return;
			

		}
		
		// E
		public function execute_autologon()
		{
			global $g_cuteengine;
			//echo "execute_autologon<br>";
			$local_login_field = $g_cuteengine->login_field;
			if (isset($local_login_field) && ($local_login_field->is_autologin_actived()))
				$local_login_field->execute_verification_action();
		}
		// F
		public function free_user_info()
        {
			global $g_cuteengine;
			if (! isset($g_cuteengine->user))
			{
				echo "RE-CREATE USER<br>";
				$g_cuteengine->user = new t_user;
				
			}	
			$g_cuteengine->user->set_info('','','',0);	

		}		
        //  G  //
        public function get_absolute_file_path()
        {
            return CUTEENGINE_PATH;
        }        
        public function get_absolute_web_file_path($a_end_with_separator = true)
        {
            if ($a_end_with_separator)
                return 'http://'.$this->current_domian.DIRECTORY_SEPARATOR.SITE_FOLDER.DIRECTORY_SEPARATOR;
            else    
                if (SITE_FOLDER != '')
                    return 'http://'.$this->current_domian.DIRECTORY_SEPARATOR.SITE_FOLDER;
                else
                    return 'http://'.$this->current_domian;

            
        }          
        public function get_absolute_style_file_path($a_end_with_separator = true)
        {
            if (file_exists(CUTEENGINE_PATH_SITES.$this->current_site))
            {
                $local_site = $this->current_site;
            }
            else
            {
                $local_site = 'default';
            }
            if ($a_end_with_separator)
                return CUTEENGINE_PATH_SITES.$local_site.DIRECTORY_SEPARATOR;
            else    
                return CUTEENGINE_PATH_SITES.$local_site;
        }
        public function get_absolute_web_style_file_path()
        {
            if (file_exists(CUTEENGINE_PATH_SITES.$this->current_site))
            {
                $local_site = $this->current_site;
            }
            else
            {
                $local_site = 'default';
            }
            return $this->get_absolute_web_file_path().SOURCE_FOLDER.DIRECTORY_SEPARATOR.'sites'.DIRECTORY_SEPARATOR.$local_site.DIRECTORY_SEPARATOR;
        }
		
		
        public function get_date_validation_method_content($a_param_name)    
        {
            $local_prepare = '';
            $local_test = '';
            foreach ($this->date_validation_strings As $local_index => $local_string)
            {
                $local_prepare .= "var re_$local_index = $local_string;\n";
                if ($local_test == '')
                    $local_test = "return (re_$local_index.test($a_param_name)";
                else
                    $local_test .= " || re_$local_index.test($a_param_name)";
            }
            $local_test .= ');';
            return $local_prepare.$local_test;
        }
		
		public function get_money_validation_method_content($a_param_name)    
        {
            $local_prepare = '';
            $local_test = '';
            foreach ($this->money_validation_strings As $local_index => $local_string)
            {
                $local_prepare .= "var re_$local_index = $local_string;\n";
                if ($local_test == '')
                    $local_test = "return (re_$local_index.test($a_param_name)";
                else
                    $local_test .= " || re_$local_index.test($a_param_name)";
            }
            $local_test .= ');';
            return $local_prepare.$local_test;
        }
        public function get_time_validation_method_content($a_param_name)    
        {
            $local_prepare = '';
            $local_test = '';
            foreach ($this->time_validation_strings As $local_index => $local_string)
            {
                $local_prepare .= "var re_$local_index = $local_string;\n";
                if ($local_test == '')
                    $local_test = "return (re_$local_index.test($a_param_name)";
                else
                    $local_test .= " || re_$local_index.test($a_param_name)";
            }
            $local_test .= ');';
            return $local_prepare.$local_test;
        }

        public function get_file_browser_version_name($a_path,$a_suffix,$a_extension)
        {
            $local_browser = $this->user_agent->browser;
            $local_browser_version = $this->user_agent->browser_version;
            $local_result = $a_path.$a_suffix . $a_extension;
            //
            if (file_exists($a_path.$a_suffix . "_" . $local_browser . "_" . $local_browser_version . $a_extension)) 
                $local_result = $a_path.$a_suffix . "_" . $local_browser . "_" . $local_browser_version . $a_extension;
            else if (file_exists($a_path.$a_suffix . "_" . $local_browser . $a_extension))
                $local_result = $a_path.$a_suffix . "_" . $local_browser . $a_extension;
            //
			//echo "local_result: $local_result<br>";
            return $local_result;    
        }
        
        public function get_line_ending()
        {
            if ($this->user_agent === t_user_agent_component::t_operating_system_window)
            {
                return '\r\n';
            }
            else if ($this->user_agent === t_user_agent_component::t_operating_system_mac_os)
            {
                return '\r';
            }
            else if ($this->user_agent === t_user_agent_component::t_operating_system_linux)
            {
                return '\n';
            }
            else if ($this->user_agent === t_user_agent_component::t_operating_system_other)
            {
                return '\n';
            }
            
        }
		

		
		public function get_javascript_dateime_pattern($a_php_datetime_format)    
        {
			return "/^".$a_php_datetime_format."$/";
		}
        public function get_relative_style_file_path()
        {
            return SOURCE_FOLDER.DIRECTORY_SEPARATOR.'sites'.DIRECTORY_SEPARATOR.$this->current_site.DIRECTORY_SEPARATOR;
        }
        // H
        public function hide_separator($a_str)
        {   
            $local_search[] = t_url_parameter::ampersand_format; 
            $local_replace[] = t_url_parameter::hide_ampersand; 
            $local_search[] =  t_url_parameter::component_format; 
            $local_replace[] = t_url_parameter::hide_component;
            $local_search[] = t_url_parameter::argument_format; 
            $local_replace[] = t_url_parameter::hide_argument; 
            $local_search[] = t_url_parameter::method_format; 
            $local_replace[] = t_url_parameter::hide_method; 
            $local_search[] = t_url_parameter::separator_level_0; 
            $local_replace[] = t_url_parameter::hide_separator_level_0; 
            $local_search[] =  t_url_parameter::separator_level_1; 
            $local_replace[] = t_url_parameter::hide_separator_level_1;
            
            return str_replace($local_search, $local_replace,$a_str);
        }	
        // I
        public function is_session_started()
        {
            return (!(session_id() == ''));
        }
		public function is_there_a_logged_user()
        {
			global $g_cuteengine;
			$local_return = ((isset($g_cuteengine->user)) && ($g_cuteengine->user->email != ''));
			return $local_return;
			

		}	
		// L
		public function load_custom_language($a_obj,$a_name)
		{
			//echo __METHOD__;
            global $g_ambient_namespace;
			$local_language_position_last = ($a_obj->get_language_position_last()) - 1;
			
			$local_file_name = $a_name;
			$local_file_name = CUTEENGINE_CUSTOM_LANGUAGES_PATH.$g_ambient_namespace->language.DIRECTORY_SEPARATOR.$local_file_name."_lang.php";
			if (($local_language_position_last > 0) /*&& (file_exists($local_file_name))*/)
			{
				//echo "local_file_name: $local_file_name<br>";
				require($local_file_name);
			}	
			$local_sentences_count = $a_obj->get_lang_count();	
			if ($local_sentences_count != $local_language_position_last)
				throw new Exception("ERROR, for '$a_name' field didn't define enough sentences ($local_sentences_count instead of $local_language_position_last)");
		}        
		public function load_language($a_obj)
		{
			global $g_ambient_namespace;
			$local_language_position_last = ($a_obj->get_language_position_last()) - 1;
			
			$local_class_name = get_class($a_obj);
			$local_file_name = substr($local_class_name,2);
			$local_file_name = CUTEENGINE_LANGUAGES_COMPONENTS_PATH.$g_ambient_namespace->language.DIRECTORY_SEPARATOR.$local_file_name."_lang.php";
			if (($local_language_position_last > 0) /*&& (file_exists($local_file_name))*/)
			{
				//echo "local_file_name: $local_file_name<br>";
				require($local_file_name);
			}	
			$local_sentences_count = $a_obj->get_lang_count();	
			if ($local_sentences_count != $local_language_position_last)
				throw new Exception("ERROR, for '$local_class_name' class didn't define enough sentences ($local_sentences_count instead of $local_language_position_last)");
		}

        // O 
        public function open_db_connection()
        {
            $this->connection->open_connection();
            $this->log->add_log_on_page("CONNESISONE A DB APERTA");
			
        }
        // R
        public function remove_hide_separator($a_str)
        {   
            $local_search[] = t_url_parameter::hide_ampersand; 
            $local_replace[] = t_url_parameter::ampersand_format; 
            $local_search[] = t_url_parameter::hide_component; 
            $local_replace[] = t_url_parameter::component_format; 
            $local_search[] = t_url_parameter::hide_argument; 
            $local_replace[] = t_url_parameter::argument_format; 
            $local_search[] = t_url_parameter::hide_method; 
            $local_replace[] = t_url_parameter::method_format; 
            $local_search[] = t_url_parameter::hide_separator_level_0; 
            $local_replace[] = t_url_parameter::separator_level_0; 
            $local_search[] = t_url_parameter::hide_separator_level_1; 
            $local_replace[] = t_url_parameter::separator_level_1; 
            
            return str_replace($local_search, $local_replace,$a_str);
        }	
        // S
        public function set_international_option($a_name)    
        {
            //echo "a_name: $a_name<br>";
			global $g_javascript_namespace;
			$local_file_name = CUTEENGINE_NAMESPACES_PATH."int_opt".DIRECTORY_SEPARATOR.strtolower($a_name)."_int_opt.php";
			global $g_ambient_namespace;
            //echo "local_file_name: $local_file_name<br>";
			require($local_file_name);
			setlocale(LC_MONETARY, $g_ambient_namespace->money_local);
            $g_javascript_namespace->header_script_generator->add_method_to_a_class_with_content/*replace_content_of_a_method*/("String",
                "validate_date","a_date",$g_ambient_namespace->get_date_validation_method_content("a_date"));
            $g_javascript_namespace->header_script_generator->add_method_to_a_class_with_content/*replace_content_of_a_method*/("String",
                "validate_time","a_time",$g_ambient_namespace->get_time_validation_method_content("a_time"));
			 $g_javascript_namespace->header_script_generator->add_method_to_a_class_with_content
			/*replace_content_of_a_method*/("String",
                "validate_money","a_money",$g_ambient_namespace->get_money_validation_method_content("a_money"));
        }


        public function start_session()
        {
            global $g_url_parameters_namespace;
            // Session
            $this->cookie_request = session_get_cookie_params();
			//print_r($this->cookie_request);
            //
            if (! $this->is_session_started())
            {
                if ((array_key_exists('sid',$_POST)))
					session_id($_POST['sid']);	
						
				if (isset($this->before_start_session))
                    $this->before_start_session();
                //    
				
                if ($g_url_parameters_namespace->current_site == 'offline') 
                {
                    
                    session_start();
                    ob_end_flush();
                    //echo "ciao";
                    //print_r(ob_list_handlers());
                    //ob_end_flush();
                    //ob_flush();
                    //ob_start('ob_gzhandler') ;
                }    
                else    
                {
                    ob_end_clean();
					//session_start();	
                   // 
					//ob_start('ob_gzhandler',1) ;
					if ($g_url_parameters_namespace->fast_parameter == '')
					{
						session_start();	 
					    if(!ob_start("ob_gzhandler")) ob_start();
						header('Content-Type:text/html; charset=UTF-8');
					}
					else
					{	
						ob_start() ;
						//session_start();	
                   // 
						//Header( "Location: http://www.workly.it");
					}
						
					//ECHO "NEW SESSION STERTED ID: " . session_id();
                }    
                //ob_start() ;
                $this->log->add_log_on_page('creates session_id: ' . session_id());
            }
            else
            {	
                if ($g_url_parameters_namespace->current_site == 'offline')                
                    ob_flush();
                else    
                {
                    ob_end_clean();
					ECHO "OLD SESSION ACTIVED ID: " . session_id();
                    if(!ob_start("ob_gzhandler")) ob_start();
					if ($g_url_parameters_namespace->fast_parameter === '') 
						header('Content-Type:text/html; charset=UTF-8');
					/*else
						Header( "Location: http://www.workly.it");*/
                }    
                $this->log->add_log_on_page('session_id: ' . session_id() . 'already exists.');
            }
            $this->log->reset_error_count();
        } 
		// S
		public function set_user_info($a_email,$a_groups,$a_name,$a_id)
        {
			global $g_cuteengine;
			
			if (! isset($g_cuteengine->user))
			{
				//echo "RE-CREATE USER<br>";
				$g_cuteengine->user = new t_user;
				
			}	
			$g_cuteengine->user->set_info($a_email,$a_groups,$a_name,$a_id);	

		}
		
		
		
			
    }
    //echo "1 <br>";
    if (!defined('PHP_VERSION_ID'))    
    {
        $version = explode('.', PHP_VERSION);
        define('PHP_VERSION_ID', ($version[0] * 10000 + $version[1] * 100 + $version[2]));
    }
    global $g_ambient_namespace;
    $g_ambient_namespace = new t_ambient_namespace;
	
?>    